package com.yin.ketech.config.security;

import com.yin.ketech.util.RedisTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CustomerAuthenticationTokenFilter
 * @Author luzw
 * @Description
 * @Version V1.0
 * @Date 2020/6/2 16:47
 **/
@Slf4j
public class CustomerAuthenticationTokenFilter extends OncePerRequestFilter {

    private UserDetailsService userDetailsService;

    private RedisTokenUtils redisTokenUtils;

    public CustomerAuthenticationTokenFilter(UserDetailsService userDetailsService, RedisTokenUtils redisTokenUtils){
        this.userDetailsService = userDetailsService;
        this.redisTokenUtils = redisTokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(RedisTokenUtils.TOKEN_HEADER);
        if (authHeader != null && authHeader.startsWith(RedisTokenUtils.TOKEN_PARSE_PREFIX)) {
            final String authToken = authHeader.substring(RedisTokenUtils.TOKEN_PARSE_PREFIX.length());
            String username = redisTokenUtils.getUsername(authToken);
            if(username != null){
                redisTokenUtils.refreshTokenIfExpiringSoon(authToken);
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    if (userDetails != null) {
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    } else {
                        redisTokenUtils.removeToken(authToken);
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}
